package com.aispeech.asr.clib.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.ToString;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SplittedPcmData {
    private List<Offset> offsetList;
    private ByteBuf buffer;

    public SplittedPcmData() {
        buffer = Unpooled.buffer();
        offsetList = new ArrayList<>();
    }

    public List<Offset> getOffsetList() {
        return offsetList;
    }

    public void addOffset(int begin, int end) {
//        System.out.println(String.format("[ addOffset ] offset: %d", offset));
        offsetList.add(new Offset(begin, end));
    }

    public void write(byte[] bytes) throws IOException {
        buffer.writeBytes(bytes);
    }

    public int length() {
        return buffer.readableBytes();
    }
    
    public ByteBuf getBuffer() {
    	return buffer;
    }
    
    public int writerIndex() {
        return buffer.writerIndex();
    }

    public byte[] feed(int begin, int end) {
        buffer.readerIndex(begin);
//        System.out.println(String.format("[ feed ] length: %d, index: %d, total: %d", length, buffer.readerIndex(), length()));
        int length = end - begin;
        byte[] bytes = new byte[length];
        buffer.readBytes(bytes, 0, length);

        return bytes;
    }    

    @ToString
    public class Offset {
        private int begin;
        private int end;

        public Offset(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }

        public int getBegin() {
            return begin;
        }

        public int getEnd() {
            return end;
        }
    }
}
